package org.jianfa.homework.user.service.impl;

import org.jianfa.homework.user.mapper.JianfaTokenMapper;
import org.jianfa.homework.user.model.JianfaToken;
import org.jianfa.homework.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    public JianfaTokenMapper jianfaTokenMapper;

    /**
     * isRegistered
     * 是否已注册，根据邮箱判断
     * true代表已经注册过
     * false代表尚未注册
     *
     * @param email
     * @return
     */
    public boolean isRegistered(String email) {
        JianfaToken jianfaToken = jianfaTokenMapper.selectByEmail(email);
        return jianfaToken == null ? false : true;
    }

    /**
     * register
     * token存入数据库
     *
     * @param email
     * @param password
     * @param token
     * @return
     */
    public boolean register(String email,  String password, String token) {
        JianfaToken jianfaToken = new JianfaToken();
        jianfaToken.setEmail(email);
        jianfaToken.setPassword(password);
        jianfaToken.setToken(token);
        int insert = jianfaTokenMapper.insert(jianfaToken);
        return insert > 0 ? true : false;
    }

    public JianfaToken getJianfaToken(String token) {
        JianfaToken jianfaToken = jianfaTokenMapper.selectByToken(token);
        return jianfaToken;
    }

    public boolean authenticate(String email, String password) {
        JianfaToken jianfaToken = jianfaTokenMapper.selectByEmail(email);
        if (jianfaToken == null) {
            return false;
        }

        String realPassword = jianfaToken.getPassword();
        if (realPassword.equals(password)) {
            return true;
        }

        return false;
    }

    @Override
    public boolean updateToken(String email, String token) {
        int update = jianfaTokenMapper.updateTokenByEmail(email, token);
        return update > 0 ? true : false;
    }
}
